{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"A very simple MNIST classifier\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "import math\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "FLAGS = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-2-d7d514ac5c52>:5: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From C:\\Program\\Anaconda2\\envs\\python3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From C:\\Program\\Anaconda2\\envs\\python3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting C:/Users/Administrator/workspace/homework6/courseware\\train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From C:\\Program\\Anaconda2\\envs\\python3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting C:/Users/Administrator/workspace/homework6/courseware\\train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From C:\\Program\\Anaconda2\\envs\\python3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting C:/Users/Administrator/workspace/homework6/courseware\\t10k-images-idx3-ubyte.gz\n",
      "Extracting C:/Users/Administrator/workspace/homework6/courseware\\t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From C:\\Program\\Anaconda2\\envs\\python3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n"
     ]
    }
   ],
   "source": [
    "# 我们在这里调用系统提供的Mnist数据函数为我们读入数据，如果没有下载的话则进行下载\n",
    "# 这里将data_dir改为适合你的运行环境的目录\n",
    "# import data\n",
    "data_dir = 'C:/Users/Administrator/workspace/homework6/courseware'\n",
    "mnist = input_data.read_data_sets(data_dir,one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "# 输入\n",
    "in_units = 784 # 输入节点数\n",
    "x = tf.placeholder(tf.float32,[None,in_units])\n",
    "\n",
    "# 转成1*28*28*1的矩阵,batch x height x width x channels\n",
    "with tf.name_scope('reshape'):\n",
    "    x_image = tf.reshape(x,[-1,28,28,1])\n",
    "\n",
    "# 进入全连接层的宽、高\n",
    "out_width = 0\n",
    "out_height= 0\n",
    "\n",
    "# 第一个卷积层 height x width x in_channels x out_channels\n",
    "outchannel_1 = 64 # 输出通道\n",
    "with tf.name_scope('conv1'):\n",
    "    ksize_conv1 = 6\n",
    "    shape = [ksize_conv1,ksize_conv1,1,outchannel_1] # 1*32个5 x 5 卷积核\n",
    "    W_conv1 = tf.Variable(tf.truncated_normal(shape, stddev=0.1),\n",
    "                         collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "    shape = [outchannel_1]\n",
    "    b_conv1 = tf.Variable(tf.constant(0.1,shape=shape))\n",
    "    strides_shape_conv1 = [1,1,1,1]\n",
    "    l_conv1 = tf.nn.conv2d(x_image,W_conv1, strides=strides_shape_conv1,\n",
    "                          padding='SAME') + b_conv1\n",
    "    h_conv1 = tf.nn.relu(l_conv1)\n",
    "    \n",
    "    out_height = math.ceil(float(28) / float(strides_shape_conv1[1]))\n",
    "    out_width  = math.ceil(float(28) / float(strides_shape_conv1[2]))\n",
    "    \n",
    "# 第一个池化层\n",
    "with tf.name_scope('pool1'):\n",
    "    ksize_1 = 3\n",
    "    strides_1 = 3\n",
    "    ksize_shape_pool1 = [1,ksize_1,ksize_1,1]\n",
    "    strides_shape_pool1 = [1,strides_1,strides_1,1]\n",
    "    h_pool1 = tf.nn.max_pool(h_conv1, ksize=ksize_shape_pool1,strides=strides_shape_pool1, padding='VALID')\n",
    "    \n",
    "    out_height = math.ceil(float(out_height - ksize_shape_pool1[1] + 1) / float(strides_shape_pool1[1]))\n",
    "    out_width  = math.ceil(float(out_width - ksize_shape_pool1[2] + 1) / float(strides_shape_pool1[2]))\n",
    "                      \n",
    "# 第二层卷积层 32 个特征map 生成 64个特征map\n",
    "outchannel_2 = 128 # 输出通道\n",
    "with tf.name_scope('conv2'):\n",
    "    ksize_conv2 = 5\n",
    "    shape = [ksize_conv2,ksize_conv2,outchannel_1,outchannel_2] # 32*64个5 x 5 卷积核\n",
    "    W_conv2 = tf.Variable(tf.truncated_normal(shape,stddev=0.1),\n",
    "                         collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "    shape = [outchannel_2]\n",
    "    b_conv2 = tf.Variable(tf.constant(0.1,shape=shape))\n",
    "    \n",
    "    strides_shape_conv2 = [1,1,1,1]\n",
    "    l_conv2 = tf.nn.conv2d(h_pool1,W_conv2, strides=strides_shape_conv2,\n",
    "                          padding='SAME') + b_conv2\n",
    "    h_conv2 = tf.nn.relu(l_conv2)\n",
    "                      \n",
    "    out_height = math.ceil(float(out_height) / float(strides_shape_conv2[1]))\n",
    "    out_width  = math.ceil(float(out_width) / float(strides_shape_conv2[2]))\n",
    "    \n",
    "# 第二层池化层\n",
    "with tf.name_scope('pool2'):\n",
    "    ksize_2 = 2\n",
    "    strides_2 = 2\n",
    "    ksize_shape_pool2 = [1,ksize_2,ksize_2,1]\n",
    "    strides_shape_pool2 = [1,strides_2,strides_2,1]\n",
    "    h_pool2 = tf.nn.max_pool(h_conv2, ksize=ksize_shape_pool2,\n",
    "                            strides=strides_shape_pool2,padding='VALID')\n",
    "    out_height = math.ceil(float(out_height - ksize_shape_pool2[1] + 1) / float(strides_shape_pool2[1]))\n",
    "    out_width  = math.ceil(float(out_width - ksize_shape_pool2[2] + 1) / float(strides_shape_pool2[2]))\n",
    "    \n",
    "# 全连接层，经过两次卷积、池化后，28 x 28图片，降维成64个7 x 7的特征map\n",
    "#28 x 28 1\n",
    "#28 x 28 32\n",
    "#14 x 14 32\n",
    "\n",
    "#14 x 14 64\n",
    "#7 x 7 64\n",
    "# 64个7 x 7特征map，通过全连接输出 h1_units 个\n",
    "\n",
    "# 隐含层1\n",
    "h1_units = 1024 # 隐含层的输出节点数\n",
    "print(out_height)\n",
    "print(out_width)\n",
    "\n",
    "with tf.name_scope('fc1'):\n",
    "    W_fc1 = tf.Variable(tf.truncated_normal([out_height*out_width*outchannel_2,h1_units], stddev=0.1),\n",
    "                       collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "    b_fc1 = tf.Variable(tf.constant(0.1,shape=[h1_units]))\n",
    "    h_pool2_flat = tf.reshape(h_pool2,[-1,out_height*out_width*outchannel_2])\n",
    "    #h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1) +  b_fc1)# 0.9703\n",
    "    h_fc1 = tf.nn.relu6(tf.matmul(h_pool2_flat,W_fc1) +  b_fc1)# 0.9711\n",
    "    \n",
    "    #h1=tf.nn.sigmoid(tf.matmul(x,W1)+b1)\n",
    "    #h1=tf.nn.tanh(tf.matmul(x,W1)+b1)\n",
    "    #h1=tf.nn.relu(tf.matmul(x,W1)+b1)\n",
    "    #h1=tf.nn.relu6(tf.matmul(x,W1)+b1)\n",
    "    #h1=tf.nn.elu(tf.matmul(x,W1)+b1)\n",
    "    #h1=tf.nn.softsign(tf.matmul(x,W1)+b1)\n",
    "# Dropout - controls the complexity of the model, prevents co-adaptation of features\n",
    "with tf.name_scope('dropout'):\n",
    "    keep_prob = tf.placeholder(tf.float32)\n",
    "    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n",
    "    \n",
    "\n",
    "    \"\"\"\n",
    "# 隐含层2\n",
    "h2_units = 50 # 隐含层2的输入节点数，这层不能多\n",
    "with tf.name_scope('fc2'):\n",
    "    W_fc2 = tf.Variable(tf.truncated_normal([h1_units,h2_units],stddev=0.1),\n",
    "                       collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "    b_fc2 = tf.Variable(tf.constant(0.1,shape=[h2_units]))\n",
    "    h_fc2 = tf.nn.relu(tf.matmul(h_fc1_drop,W_fc2) + b_fc2)\n",
    "    \n",
    "    #h2=tf.nn.sigmoid(tf.matmul(h1,W2)+b2)\n",
    "    #h2 = tf.nn.softmax(tf.matmul(h1,W2) + b2)\n",
    "    #h2 = tf.nn.tanh(tf.matmul(h1,W2) + b2)\n",
    "    #h2 = tf.nn.relu(tf.matmul(h1,W2) + b2)\n",
    "    #h2 = tf.nn.relu6(tf.matmul(h1,W2) + b2)\n",
    "    #h2 = tf.nn.elu(tf.matmul(h1,W2) + b2)\n",
    "    #h2 = tf.nn.softsign(tf.matmul(h1,W2) + b2)\n",
    "\n",
    "# 输出层\n",
    "with tf.name_scope('fc3'):\n",
    "    W_fc3 = tf.Variable(tf.truncated_normal([h2_units,10],stddev=0.1),\n",
    "                    collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "    b_fc3 = tf.Variable(tf.constant(0.1,shape=[10]))\n",
    "\n",
    "    # 使用softmax作为多分类问题的激活函数\n",
    "    #y = tf.nn.softmax(tf.matmul(h_fc2,W_fc3) + b_fc3)\n",
    "    y = tf.matmul(h_fc2,W_fc3) + b_fc3\n",
    "# 调试：两个隐层，没提高准确率，不过隐层减到一层，也不行\n",
    "\"\"\"\n",
    "\"\"\"只有一层隐层的\"\"\"\n",
    "# 输出层\n",
    "with tf.name_scope('fc3'):\n",
    "    W_fc3 = tf.Variable(tf.truncated_normal([h1_units,10],stddev=0.1),\n",
    "                    collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "    b_fc3 = tf.Variable(tf.constant(0.1,shape=[10]))\n",
    "\n",
    "    # 使用softmax作为多分类问题的激活函数\n",
    "    #y = tf.nn.softmax(tf.matmul(h_fc2,W_fc3) + b_fc3)\n",
    "    y = tf.matmul(h_fc1_drop,W_fc3) + b_fc3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义我们的ground truth占位符\n",
    "# Define loss and optimizer\n",
    "y_ = tf.placeholder(tf.float32,[None,10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-5-70d331ee7ba1>:13: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See @{tf.nn.softmax_cross_entropy_with_logits_v2}.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 接下来我们计算交叉熵，注意softmax_cross_entropy_with_logits的logits参数是未经激活的wx+b\n",
    "#cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_,logits=y))\n",
    "# L1、L2\n",
    "#w = tf.Variable(tf.random_normal([h2_units,10]),dtype=tf.float32)\n",
    "#w = tf.Variable(tf.truncated_normal([h2_units,10],stddev=0.1)) # 不同的初始化:\n",
    "#vlambda = 0.0055 \n",
    "\n",
    "#cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[0])) \n",
    "#cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y) + tf.contrib.layers.l2_regularizer(vlambda)(w),reduction_indices=[1]))\n",
    "#cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y) + tf.contrib.layers.l1_regularizer(vlambda)(w),reduction_indices=[1]))\n",
    "\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "\n",
    "l2_loss = tf.add_n( [tf.nn.l2_loss(w) for w in tf.get_collection('WEIGHTS')] )\n",
    "cross_entropy = cross_entropy + 7e-5*l2_loss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 生成一个训练step\n",
    "learing_rate = tf.placeholder(tf.float32)\n",
    "\n",
    "train_step = tf.train.GradientDescentOptimizer(learing_rate).minimize(cross_entropy)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step 100, entropy loss:1.046655\n",
      "0.93\n",
      "step 200, entropy loss:1.005117\n",
      "0.93\n",
      "step 300, entropy loss:0.942419\n",
      "0.97\n",
      "step 400, entropy loss:0.780938\n",
      "0.97\n",
      "step 500, entropy loss:0.760242\n",
      "0.99\n",
      "0.9578\n",
      "step 600, entropy loss:0.778784\n",
      "0.99\n",
      "0.9616\n",
      "step 700, entropy loss:0.782513\n",
      "0.96\n",
      "step 800, entropy loss:0.765286\n",
      "0.93\n",
      "step 900, entropy loss:0.864201\n",
      "0.92\n",
      "step 1000, entropy loss:0.772190\n",
      "0.94\n",
      "step 1100, entropy loss:0.691674\n",
      "0.96\n",
      "step 1200, entropy loss:0.650481\n",
      "1.0\n",
      "0.9706\n",
      "step 1300, entropy loss:0.643929\n",
      "0.99\n",
      "0.9731\n",
      "step 1400, entropy loss:0.735096\n",
      "0.99\n",
      "0.9726\n",
      "step 1500, entropy loss:0.716861\n",
      "0.98\n",
      "0.9741\n",
      "step 1600, entropy loss:0.702962\n",
      "0.99\n",
      "0.9743\n",
      "step 1700, entropy loss:0.698599\n",
      "0.99\n",
      "0.9756\n",
      "step 1800, entropy loss:0.648991\n",
      "0.98\n",
      "0.9721\n",
      "step 1900, entropy loss:0.656023\n",
      "0.99\n",
      "0.978\n",
      "step 2000, entropy loss:0.648010\n",
      "0.99\n",
      "0.9791\n",
      "step 2100, entropy loss:0.776653\n",
      "0.97\n",
      "step 2200, entropy loss:0.684198\n",
      "0.96\n",
      "step 2300, entropy loss:0.715798\n",
      "0.98\n",
      "0.9776\n",
      "step 2400, entropy loss:0.713374\n",
      "1.0\n",
      "0.9788\n",
      "step 2500, entropy loss:0.660302\n",
      "0.98\n",
      "0.9805\n",
      "step 2600, entropy loss:0.651893\n",
      "1.0\n",
      "0.9805\n",
      "step 2700, entropy loss:0.686055\n",
      "1.0\n",
      "0.9804\n",
      "step 2800, entropy loss:0.640705\n",
      "1.0\n",
      "0.9801\n",
      "step 2900, entropy loss:0.662573\n",
      "0.99\n",
      "0.9807\n",
      "step 3000, entropy loss:0.624773\n",
      "1.0\n",
      "0.9829\n"
     ]
    }
   ],
   "source": [
    "# 在这里我们仍然调用系统提供的读取数据，为我们取得一个batch。然后我们运行3k个step（5 epochs 5训练次数），对权重进行优化\n",
    "for step in range(3000):\n",
    "    batch_xs,batch_ys = mnist.train.next_batch(100)\n",
    "    lr = 0.05\n",
    "    \n",
    "    \"\"\"\n",
    "    if step > 700:\n",
    "        #lr = 0.05 # 0.9741\n",
    "        lr = 0.01    \n",
    "    \"\"\"\n",
    "    \n",
    "    _,loss = sess.run([train_step,cross_entropy], feed_dict={x:batch_xs,y_:batch_ys,learing_rate:lr,keep_prob:0.5})\n",
    "    \n",
    "    if (step + 1) % 100 == 0:\n",
    "        print('step %d, entropy loss:%f' %(step + 1,loss))\n",
    "        \n",
    "        correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))\n",
    "        accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n",
    "        accuracy_v = sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob:0.5})\n",
    "        print(accuracy_v)\n",
    "        if accuracy_v >= 0.98:\n",
    "            print(sess.run(accuracy, feed_dict={x:mnist.test.images,y_:mnist.test.labels,keep_prob:0.5}))\n",
    "\n",
    "    #if (step + 1) % 1000 == 0:\n",
    "    #    print(sess.run(accuracy, feed_dict={x:mnist.test.images,y_:mnist.test.labels,keep_prob:0.5}))\n",
    "   "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9813\n"
     ]
    }
   ],
   "source": [
    "# 验证我们模型在测试数据上的准确率\n",
    "# Test trained model\n",
    "correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n",
    "print(sess.run(accuracy, feed_dict={x:mnist.test.images,y_:mnist.test.labels,keep_prob:0.5}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
